<template>
  <view class="content ss-p-20">
    <x-nav-bar title="新增成长" />
    <uni-forms border>
      <uni-forms-item label="记录日期" required>
        <uni-datetime-picker v-model="sendData.recordTime" type="date" :end="new Date().getTime()"
          @change="onChangeTime">
          <button class="ss-reset-button" style="justify-content: start; color: #bbb;" @click="showBtn = false">
            <text :class="{cl:isVal}">{{ dateFilterText }}</text>
          </button>
        </uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item label="类型" required>
        <uni-data-checkbox v-model="sendData.recordType" multiple :localdata="hobbys" @change="changeType" />
      </uni-forms-item>

      <uni-forms-item label="身高" v-if="sendData.recordType.includes(1)" required>
        <uni-easyinput placeholder="请输入身高" v-model="sendData.height" type="number" :inputBorder="false">
          <template #right>
            <view>CM</view>
          </template>
        </uni-easyinput>
        <text class="his" v-if="preInfo.height">上个记录 {{dayjs().format('YYYY-MM-DD',preInfo.hlastTime)}}
          {{preInfo.height}}CM</text>
      </uni-forms-item>
      <uni-forms-item label="体重" v-if="sendData.recordType.includes(2)" required>
        <uni-easyinput type="number" v-model="sendData.weight" :trim="true" :inputBorder="false" placeholder="请输入体重">
          <template #right>
            <view>KG</view>
          </template>
        </uni-easyinput>
        <text class="his" v-if="preInfo.weight">上个记录 {{dayjs().format('YYYY-MM-DD',preInfo.hlastTime)}}
          {{preInfo.weight}}KG</text>
      </uni-forms-item>
      <uni-forms-item label="左眼视力" v-if="sendData.recordType.includes(3)" required>
        <uni-easyinput type="text" v-model="sendData.leftEye" :trim="true" :inputBorder="false" placeholder="请输入左眼视力" />
        <text class="his" v-if="preInfo.leftEye">上个记录 {{dayjs().format('YYYY-MM-DD',preInfo.hlastTime)}}
          {{preInfo.leftEye}}</text>
      </uni-forms-item>
      <uni-forms-item label="右眼视力" v-if="sendData.recordType.includes(3)" required>
        <uni-easyinput type="text" v-model="sendData.rightEye" :trim="true" :inputBorder="false"
          placeholder="请输入右眼视力" />
        <text class="his" v-if="preInfo.rightEye">上个记录 {{dayjs().format('YYYY-MM-DD',preInfo.hlastTime)}}
          {{preInfo.rightEye}}</text>
      </uni-forms-item>
      <uni-forms-item label="左眼散光" v-if="sendData.recordType.includes(3)" required>
        <uni-easyinput type="text" v-model="sendData.leftAstigmia" :trim="true" :inputBorder="false"
          placeholder="请输入左眼散光" />
        <text class="his" v-if="preInfo.leftAstigmia">上个记录 {{dayjs().format('YYYY-MM-DD',preInfo.hlastTime)}}
          {{preInfo.leftAstigmia}}</text>
      </uni-forms-item>
      <uni-forms-item label="右眼散光" v-if="sendData.recordType.includes(3)" required>
        <uni-easyinput type="text" v-model="sendData.rightAstigmia" :trim="true" :inputBorder="false"
          placeholder="请输入右眼散光" />
        <text class="his" v-if="preInfo.rightAstigmia">上个记录 {{dayjs().format('YYYY-MM-DD',preInfo.hlastTime)}}
          {{preInfo.rightAstigmia}}</text>
      </uni-forms-item>
      <uni-forms-item label="瞳距" v-if="sendData.recordType.includes(3)" required>
        <uni-easyinput type="text" v-model="sendData.pupilDistance" :trim="true" :inputBorder="false"
          placeholder="请输入瞳距" />
        <text class="his" v-if="preInfo.pupilDistance">上个记录 {{dayjs().format('YYYY-MM-DD',preInfo.hlastTime)}}
          {{preInfo.pupilDistance}}</text>
      </uni-forms-item>
      <uni-forms-item>
        <uni-easyinput type="textarea" v-model="sendData.content" :trim="true" :inputBorder="false"
          placeholder="写写你发现的进步和感动的地方" />
      </uni-forms-item>

    </uni-forms>
    <view class="ss-flex">
      <view class="img-list ss-flex ss-flex-wrap">
        <template v-if="sendData.filePath.path && sendData.filePath.path.length && isImage">
          <su-image v-for="(item,index) in sendData.filePath.path" :key="index" class="ss-m-r-10 ss-m-b-10" isPreview
            :current="0" :src="item" :height="200" :width="200" mode="aspectFill" />
        </template>
        <template v-else-if="sendData.filePath.path && sendData.filePath.path.length && !isImage">
          <video id="myVideo" class="ss-m-r-10 ss-m-b-10" :src="sendData.filePath.path[0]" :controls="false"></video>
        </template>
        <view class="add ss-m-r-10 ss-m-b-10" @tap="chooseVideoImage">
          <uni-icons type="plusempty" size="48" color="#fff"></uni-icons>
        </view>
      </view>
    </view>
    <su-fixed bottom placeholder bg="bg-white" v-if="showBtn">
      <view class="buy-btn" @click="publish">发表</view>
    </su-fixed>

  </view>

</template>

<script setup>
  import {
    onLoad
  } from '@dcloudio/uni-app';
  import {
    ref,
    reactive,
    computed,
    watch,
    onMounted
  } from 'vue';
  import dayjs from 'dayjs';
  import FileApi from '@/sheep/api/infra/file';
  import sheep from '@/sheep';
  import AccompanyApi from '@/sheep/api/member/accompany';
  import StudentApi from '@/sheep/api/member/student';
  let isImage = ref(true)
  let dateFilterText = ref('请选择日期')
  let isVal = ref(false)
  let showBtn = ref(true)
  let preInfo = reactive({})
  onLoad((options) => {
    sendData.studentId = options.id
    getStuDetail(sendData.studentId)
  })
  const userInfo = computed(() => sheep.$store('user').userInfo);
  const onChangeTime = (e) => {
    dateFilterText.value = e
    isVal.value = true
    showBtn.value = true
  }
  const hobbys = reactive([{
    text: '身高',
    value: 1
  }, {
    text: '体重',
    value: 2
  }, {
    text: '视力',
    value: 3
  }])
  const changeType = (e) => {
    state.model.type = ''
    state.model.type = e.detail.value
  }
  const state = reactive({
    model: {
      time: '',
      shengao: '',
      tizhong: '',
      type: ''
    }, // 个人信息
    rules: {},
  });
  const chooseVideoImage = () => {
    uni.showActionSheet({
      title: "选择上传类型",
      itemList: ['图片', '视频'],
      success: (res) => {
        if (res.tapIndex == 0) {
          chooseImages()
          isImage.value = true
        } else {
          chooseVideo()
          isImage.value = false
        }
      }
    })
  }

  let sendData = reactive({
    model: 2, // 1 陪伴，2成长
    type: 2, // |发布人类型 1家长；2主理人；3陪伴师
    studentId: '',
    recordTime: '',
    recordType: '',
    height: '',
    weight: '',
    leftEye: '',
    rightEye: '',
    pupilDistance: '',
    leftAstigmia: '',
    rightAstigmia: '',
    content: '',
    filePath: { // |文件地址(json字符串)；type=1图片、2视频|query|false|string||
      type: 1,
      path: [],
    },
  })
  // mgrType 管理员类型：1主理人，2陪伴师，3管理员
  if (userInfo.value.mgrType == 2) {
    sendData.type = 3
  }
  // 获取上一个记录的身高体重视力
  const getStuDetail = async (studentId) => {
    const res = await AccompanyApi.getGrowthRecord({
      studentId
    })
    if (res.code == 0) {
      Object.assign(preInfo, res.data);
    } else {
      uni.showToast({
        icon: 'none',
        title: res.msg,
      })
    }
  }
  let fileList = reactive([])
  // 发布朋友圈
  const publish = () => {
    console.log(sendData)
    if (!sendData.recordTime) {
      uni.showToast({
        icon: 'none',
        title: '请选择记录日期',
      })
      return
    }
    if (sendData.recordType.includes(1) && !sendData.height) {
      uni.showToast({
        icon: 'none',
        title: '请输入身高',
      })
      return
    }
    if (sendData.recordType.includes(2) && !sendData.weight) {
      uni.showToast({
        icon: 'none',
        title: '请输入体重',
      })
      return
    }
    if (sendData.recordType.includes(3) && (!sendData.leftEye || !sendData.rightEye || !sendData.leftAstigmia || !
        sendData.rightAstigmia || !sendData.pupilDistance)) {
      uni.showToast({
        icon: 'none',
        title: '请输入完整视力数据',
      })
      return
    }

    if (!sendData.content && sendData.filePath.path.length == 0) {
      uni.showToast({
        icon: 'none',
        title: '请输入发布内容',
      })
      return
    }
    if (!isImage.value) {
      sendData.filePath.type = 2
    }
    sendData.filePath = JSON.stringify(sendData.filePath)
    sendData.recordType = sendData.recordType.join(',')
    sendData.recordTime = new Date(sendData.recordTime).getTime()
    AccompanyApi.addGrowthRecord(sendData).then(res => {
      if (res.code == 0) {
        uni.showToast({
          icon: 'none',
          title: '发布成功',
        })
        sheep.$router.back()
      } else {
        uni.showToast({
          icon: 'none',
          title: res.msg,
        })
      }
    })
  }

  // 手动选择头像，进行上传
  const chooseImages = () => {
    // 选择图片文件
    uni.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      success: async (res) => {
        await uploadAvatar(res.tempFilePaths[0]);
      },
    });
  }
  const chooseVideo = () => {
    uni.chooseVideo({
      sourceType: ['camera', 'album'],
      count: 1,
      maxDuration: 60,
      success: async (res) => {
        await uploadAvatar(res.tempFilePath);
      }
    });
  }
  // 上传头像文件
  const uploadAvatar = async (tempUrl) => {
    if (!tempUrl) return
    let {
      data
    } = await FileApi.uploadFile(tempUrl);
    sendData.filePath.path.push(data)
  }
</script>

<style lang="scss" scoped>
  .buy-btn {
    width: 750rpx;
    height: 100rpx;
    line-height: 100rpx;
    font-weight: 500;
    font-size: 28rpx;
    background: linear-gradient(90deg, #ff3000, #ff300099);
    color: #fff;
    text-align: center;
  }

  .content {
    box-sizing: border-box;
    background: #fff;
    position: absolute;
    min-height: 100%;
    width: 100vw;

    .cl {
      color: #333;
    }

    .his {
      position: absolute;
      bottom: -10rpx;
      color: #999;
      font-size: 18rpx;
    }

    .img-list {
      font-size: 0;

      #myVideo,
      image {
        width: 200rpx;
        height: 200rpx;
      }

      video {
        display: block;
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
      }

    }

    .add {
      background: #eee;
      width: 200rpx;
      height: 200rpx;
      line-height: 200rpx;
      text-align: center;
    }
  }
</style>